import re

from django.utils.deprecation import MiddlewareMixin

from django.shortcuts import redirect, reverse

from js_study import settings
from app01 import models



class LoginStatusValidationMiddleware(MiddlewareMixin):

    def process_request(self, request):

        if request.session.get("logged_in"):
            user_id = request.session.get("user_id")
            request.current_user = models.User.objects.get(pk=user_id)

            return

        for url_pattern in settings.URL_WHITE_LIST:

            if re.match(url_pattern, request.path_info):

                return

        return redirect(reverse("login") + "?url=" + request.path_info)

